package org.liux.android.game.jumpgame.connect;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;

public class BluetoothServerSocketThread extends Thread {
	
	 private BluetoothAdapter mBluetoothAdapter;
	 private BluetoothDevice mBluetoothDevice;
	 private Handler mHandler;
	
	 public BluetoothServerSocketThread(BluetoothAdapter ba,BluetoothDevice bd,Handler handler){
		 	this.mBluetoothAdapter = ba;
		 	this.mBluetoothDevice = bd;
		 	this.mHandler = handler;
	 }
	 
	 public BluetoothServerSocketThread(BluetoothAdapter ba,Handler handler){
			 	this(ba,null,handler);
	 }
	 
	 public BluetoothServerSocketThread(BluetoothDevice bd,Handler handler){
		 	this(null,bd,handler);
	 }
	 
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			BluetoothSocket bs = null;
			if(mBluetoothAdapter!=null){
				BluetoothServerSocket bss = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(BlueToothManager.NAME, UUID.fromString(BlueToothManager.SPP_UUID));
				bs = bss.accept();
			}else if(mBluetoothDevice!=null){
				bs = mBluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(BlueToothManager.SPP_UUID));
				bs.connect();
			}
			
			if(bs!=null){
				sendInput(bs.getInputStream());
				sendOutput(bs.getOutputStream());

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void sendInput(InputStream is){
			Message message = mHandler.obtainMessage();
			message.what = BlueToothManager.INPUT;
			message.obj = is;
			mHandler.sendMessage(message);
	}
	
	private void sendOutput(OutputStream out){
		Message message = mHandler.obtainMessage();
		message.what = BlueToothManager.OUTPUT;
		message.obj = out;
		mHandler.sendMessage(message);
}
}
